<template>
	<w-container class="draw" :loading="loading&&!info.id">
		<w-navbar :placeholder="false" bgColor="transparent" leftIcon="arrow-left-back" left-icon-size="32" :bgColor="bgColor" :opacity="opacity" :title='pageTitle' :product="{name:'抽签活动'}">
			<template #right>
				<view class="nav-right flex flex-ai-center">
					<view @click.native='toRecord' class="record-btn">记录</view>
					<view @click.native='toRule' class="record-btn ml-10">规则</view>
				</view>
			</template>
		</w-navbar>
		<w-image src="/static/draw/draw-bg.png" mode="widthFix" width="100%"></w-image>
		<view class="draw-down-box flex flex-dir-col flex-ai-center">
			<view class="bg-color-white br-24 w-100 mt-24">
				<view class="status-text-bg">
					<view class="status-text">
						<text v-if="startStatus==0&&codeLen != info.get_draw_max">抽签开始倒计时</text>
						<text v-else-if="startStatus==1&&codeLen != info.get_draw_max">抽签结束倒计时</text>
						<text v-else>开奖时间</text>
					</view>
				</view>
				<view class="flex flex-dir-col flex-ai-center pb-24 plr-20">
					<u-count-down v-if="countDown > 0" :time="countDown" format="DD:HH:mm:ss" autoStart millisecond @finish="finish" @change="onChanges">
						<view class="time flex flex-ai-center" style="color:#7C7C7C;">
							<view v-if="timeData.days" class="time__item">{{ timeData.days }}</view>
							<view v-if="timeData.days" class="font-size-14 mlr-4">天</view>
							<view class="time__item"> {{ timeData.hours>=10?timeData.hours:'0'+timeData.hours}} </view>
							<view class=" font-size-14 mlr-4">时</view>
							<view class="time__item">{{ timeData.minutes>=10?timeData.minutes:'0' + timeData.minutes }}</view>
							<view class=" font-size-14 mlr-4">分</view>
							<view class="time__item">{{ timeData.seconds>=10?timeData.seconds:'0' + timeData.seconds }}</view>
							<view class=" font-size-14 mlr-4">秒</view>
						</view>
					</u-count-down>
					<view class="font-size-20 font-color-textPrimary" v-else>{{info.winning_time|formatDateStr}}</view>	
					<view class="status-btn-box w-100">
						<w-button v-if="codeLen&&info.winning_time*1000>nowTimestamp&&startStatus==2"  type="draw" :disabled="false" style="height: 104rpx;">等待开奖</w-button>
						<w-button v-if="!codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2"  type="draw" :disabled="true" style="height: 104rpx;">已开奖</w-button>
						<w-button v-if="codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2&&hasCheck"  type="draw" :disabled="false" style="height: 104rpx;">已中奖</w-button>
						<w-button v-if="codeLen&&info.winning_time*1000<=nowTimestamp&&startStatus==2&&!hasCheck"  type="draw" :disabled="true" style="height: 104rpx;">未中奖</w-button>
						<w-button v-if="codeLen == info.get_draw_max&&info.winning_time*1000>nowTimestamp"  type="draw" :disabled="false" style="height: 104rpx;">等待开奖</w-button>			
						<w-button v-if="startStatus==0"  type="draw" :disabled="true" style="height: 104rpx;">未开始</w-button>
						<w-button v-if="startStatus==1&&info.remaining>0&&!codeLen" @click.native='draw' type="draw" style="height: 104rpx;">立即抽奖</w-button>
						<w-button v-if="startStatus==1&&info.remaining>0&&codeLen" @click.native='draw' type="draw" style="height: 104rpx;">再抽一次</w-button>
						<w-button v-if="startStatus==1&&info.remaining_invited && info.how_people_get_draw > 1 && info.remaining == 0 && codeLen<info.get_draw_max &&codeLen" @click.native='toInvite' type="draw" style="height: 104rpx;">去邀请</w-button>
						<w-button v-if="startStatus==1&&info.remaining_invited && info.how_people_get_draw == 1 && info.remaining == 0 && codeLen<info.get_draw_max &&codeLen" @click.native='toInvite' type="draw" style="height: 104rpx;">还需邀请一人</w-button>
						<view v-if="startStatus==1&&info.remaining_invited&&codeLen" class="again_box">（<text>再</text>邀请{{info.remaining_invited}}位用户可额外获得一个签号）</view>
					
					</view>
					<view class="font-size-14 mt-15" style="color: #7C7C7C;">当前累计参与<text style="color:#F44A6C;">{{ info.all_count }}</text>次</view>
				</view>
			</view>
			
		</view>
		<view class="plr-8">
			<view class="invite-box pt-10 pl-8 pr-18 box-b mt-16">
				<view class="flex flex-ai-center flex-js-sb">
					<view class="flex flex-ai-center">
						<w-image src="/static/draw/invite-icon.png" width="58" height="58"></w-image>
						<view class="flex flex-dir-col ml-12">
							<view style="color: #4A1D2F;" class="font-size-14 font-w-500 invite-text">邀请好友（{{ all_invited_people }}/2）</view>
							<view class="font-size-10 font-color-666 mt-2"><text style="color: #FD5E43;">邀请两位新用户</text>可额外获得一个签号</view>
						</view>
					</view>
					<w-button @click.native='toInvite' style="width: 128rpx;height: 60rpx;background-color: #000000;border-radius: 38rpx;font-size: 24rpx;">去邀请</w-button>
				</view>
			</view>
			<view class="mt-16 bg-color-white br-24">
				<view class="status-text-bg">
					<w-image src="/static/draw/my-code-text.png" width="129" mode="widthFix"></w-image>
				</view>
				<view class="plr-10 pb-10">
					<view class="flex flex-ai-center flex-js-sb" :class="{isUncheck:info.winning_time*1000<=nowTimestamp&&item.status==0}"
						v-for="item in info.codeList" :key="item.draw_sn">
						<view class="font-color-black font-size-18">{{ item.draw_sn }}</view>
						<view class="xuxian"></view>
						<w-button v-if="codeLen&&info.winning_time*1000>nowTimestamp&&startStatus==2" style="width: 128rpx;height: 60rpx;background-color: #8C8B8C;color: #fff;border-radius: 38rpx;font-size: 24rpx;" :disabled="true">待开奖</w-button>
						<view v-else>
							<w-button v-if="info.winning_time*1000<=nowTimestamp&&item.status==1" style="width: 128rpx;height: 60rpx;background: #F44A6C;border-radius: 38rpx;font-size: 24rpx;color: #fff;" :disabled="false">已中奖</w-button>
							<w-button v-if="info.winning_time*1000<=nowTimestamp&&item.status==0" style="width: 128rpx;height: 60rpx;background-color: #F5F5F5;color: #898989;border-radius: 38rpx;font-size: 24rpx;" :disabled="true">未中奖</w-button>
							<w-button v-else style="width: 128rpx;height: 60rpx;background-color: #F5F5F5;color: #898989;border-radius: 38rpx;font-size: 24rpx;" :disabled="true">待开奖</w-button>
						</view>
					</view>
				</view>
				<view v-if="!info.codeList.length" class="font-color-666 ptb-38 text-center">暂无数据~</view>
			</view>
		</view>
		<u-popup :show='showNum' mode='center' bgColor='transparent' round='32rpx'>
			<view class="pt-20 num-popup flex flex-dir-col flex-js-sb flex-ai-center"> 
				<view class="flex flex-dir-col flex-ai-center">
					<image :src="$originOssUrl + '/static/draw/popup_hua.png'" style="width: 254rpx;height: 230rpx;"></image>
				</view>
				<view class="bg-color-item br-18 flex flex-dir-col flex-ai-center" style="width: 600rpx;box-sizing: border-box;margin-top: -80rpx;">
					<w-image src="/static/draw/gongxi.png" mode="widthFix" style="width: 302rpx;margin-top: 110rpx;"></w-image>
					<view class="flex flex-ai-center flex-js-sa plr-17 w-100 mt-16">
						<view v-for="item in num" :key="item" class="item-number">{{ item }}</view>
					</view>
					<view class="font-size-10 font-color-666 mt-30 mb-17">已放入我的抽签码中</view>
					<view @click="showNum = false" class="font-color-white bg-color-black w-100 ptb-15 text-center" style="border-radius: 0 0 32rpx 32rpx;">我知道了</view>
				</view>
			</view>
		</u-popup> 
		<u-popup :show='invitShow' @close="invitShow = false" @open="invitShow = true" closeOnClickOverlay mode='center' bgColor='transparent' round='32rpx'>
			<view class="flex flex-dir-col flex-ai-center">
				<image :src="$originOssUrl + '/static/draw/popup_hua.png'" style="width: 382rpx;height: 382rpx;"></image>	
				<view class="bg-color-white br-18 flex flex-dir-col flex-ai-center pb-16" style="width: 600rpx;margin-top: -180rpx;">
					<view class="font-size-16" style="color: #666;margin-top: 100rpx;">邀请二维码</view>
					<w-qrcode :content="invitaion_code" bgColor="unset"  :size="170" class="img mtb-12" @change='setQrcodeImg'></w-qrcode>
					<u-line margin="32rpx 0"></u-line>
					<!-- <view @click="draw_start" class="mb-16 font-color-black">保存二维码</view> -->
					<view class="flex flex-ai-center flex-js-sa" style="width: 70%;">
						<w-button @click="copyInviteUrl" pain size="ss">复制链接</w-button>
						<w-button @click="draw_start" size="ss">保存二维码</w-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup :show='frequencysHow' @close="frequencysHow = false" @open="frequencysHow = true" closeOnClickOverlay mode='center' bgColor='#fff' round='16rpx'>
			<view class="flex flex-dir-col flex-ai-center plr-16 ptb-24" style="width: 600rpx;">
				<view class="font-color-black font-size-16 font-w-bold font-size-14" >我的抽签次数: {{info.remaining}}</view>
				<view class="mt-8" style="color: #666;">
					<text>已邀请</text>
					<text class="font-color-textPrimary">{{ all_invited_people }}</text>
					<text>位好友预约</text>
				</view>
				<view class="flex flex-ai-center mt-18 mb-4" style="width: 100%;">
					<view style="width: 50%;color: #666;" class="text-center ">手机号</view>
					<view style="width: 50%;color: #666;" class="text-center ">邀请状态</view>
				</view>
				<scroll-view scroll-y="true" style="max-height: 60vh;">
					<view v-for="item in frequencyList" :key="item.id" class="flex flex-ai-center mt-8" style="width: 100%;">
						<view style="width: 50%;color: #222;" class="text-center ">{{item.mobile}}</view>
						<view style="width: 50%;color: #26B657;" class="text-center ">成功</view>
					</view>
				</scroll-view>
				<w-loading v-if="!frequencyList.length" type="empty" empty-type="search"></w-loading>
			</view>
		</u-popup>
		<view style="position: fixed;z-index: -1000;">
			<w-canvas :isDraw="isDraw" :canvasData="canvasData" :imageSize="{width: 343, height: 526}" @generateImageSuccessful="drawAccomplish"></w-canvas>
		</view>
		<u-gap height="30"></u-gap>
	</w-container>
</template>

<script>
	import {
		getDraw,
		draw,
		drawRecord,
		invited_record
	} from '@/api/draw/index.js'
	import {
		mapState,
		mapActions
	} from 'vuex'
	import dayjs from 'dayjs'
	import opacityMixin from '@/mixins/opacityNav.js'
	export default {
		data() {
			return {
				loading: true,
				id: null,
				showNum: false,
				info: {
					codeList: []
				},
				num: [],
				record: [],
				timeData:{},
				invitShow:false,
				isDraw:false,
				canvasData:[],
				showPoster: false,
				posterImg:'',
				frequencysHow:false,
				frequencyList:[],
				all_invited_people:0
			}
		},
		mixins: [opacityMixin],
		onLoad({
			thm
		}) {
			this.id = thm;
			this.getInfo();
			this.createNowTimeTimer()
		},
		onShow() {
			if(!this.info.id) {
				this.getInfo();
				this.createNowTimeTimer()
			}
		},
		onPullDownRefresh() {
			this.getInfo()
		},
		filters: {
			formatDateStr(v) {
				return dayjs(v * 1000).format('YYYY年MM月DD日HH:mm')
			}
		},
		computed: {
			...mapState('config', ['nowTimestamp']),
			// 邀请二维码
			invitaion_code() {
				let time = new Date().getTime();
				// 当前页面路径
				let curRoute=getCurrentPages()
				let fullUrl='/\#'+curRoute[curRoute.length-1].$page.fullPath
				
				let url=`${this.appConfig.h5_domain + '/#/pages/activity/draw?a=1'}&inviter_user_id=${this.userInfo.id}&t=${time}&thm=${this.id}`				
				return url
			},
			//开始状态
			startStatus() { //1为在中间，0在开始时间前，2在结束时间后
				return this.$tools.checkTimeBetween(this.nowTimestamp, this.info.reg_start_time * 1000, this.info
					.reg_end_time * 1000)
			},
			hasCheck() {  
				return this.info.codeList.map(v => v.status).includes('1')
			},
			//倒计时
			countDown() {
				if (this.startStatus == 0 && this.codeLen != this.info.get_draw_max) {
					return this.info.reg_start_time * 1000 - this.nowTimestamp
				} else if (this.startStatus == 1 && this.codeLen != this.info.get_draw_max) {
					return this.info.reg_end_time * 1000 - this.nowTimestamp
				}
				return this.info.winning_time * 1000 - this.nowTimestamp
			},
			formatStr() {
				if (this.countDown < 1000 * 60 * 60 * 24) {
					return 'HH:mm:ss'
				}
				return 'DD天HH:mm:ss'
			},
			//报名状态
			codeLen() {
				return this.info.codeList.length
			},		
			toRule() {
				uni.setStorage({
					data: this.info.content,
					key: 'draw-text',
					success() {
						uni.navigateTo({
							url: '/pages/rules/rules?type=6'
						})
					}
				})
			},
		},
		methods: {
			...mapActions('config', ['createNowTimeTimer']),
			getInfo() {
				this.loading = true;
				getDraw(this.id).then(res => {
					this.info = res.data;
					this.$forceUpdate()

				}).finally(() => {
					this.loading = false
					// this.getRecord();
					uni.stopPullDownRefresh()
				})
			},
			getRecord() {
				drawRecord(this.id).then(res => {

					this.record = res.data.map(v => {
						return v.nickname + "已中签"
					})
					// console.log(this.record)
				})
			},
			changefrequencysHow(){
				uni.navigateTo({
					url: '/pages/invitation/invitation'
				})
				// this.getFrequencyList()
			},
			getFrequencyList(){
				// uni.showLoading({
				// 	title:'查询中...'
				// })
				// invited_record(this.id).then( res => {
				// 	this.all_invited_people = res.data.all_invited_people
				// 	this.frequencyList = res.data.data
				// 	this.frequencysHow = true
				// })
			},
			draw() {
				uni.showLoading({
					title: "抽签中"
				})
				let form = {
					id:this.id			
				}
				if(uni.getStorageSync('inviter_user_id')) form.inviter_user_id = uni.getStorageSync('inviter_user_id')
				draw(form).then(res => {
					this.num = res.data;
					if(this.num) {
						this.num = Array.from(this.num)
					}
					uni.removeStorageSync('inviter_user_id')
					this.showNum = true;
				}).finally(() => {
					this.getInfo();
				})
			},
			toInvite() {
				uni.navigateTo({
					url: '/pages/invitation/invitation'
				})
				// this.invitShow = true
			},
			toRecord() {
				uni.navigateTo({
					url: '/pages/activity/record?id=' + this.id
				})
			},
			finish(){
				this.$emit('finish')
			},
			onChanges(e) {
				this.timeData = e
			},
			playVideoJump(){
				if(!this.info.draw_video) {
					uni.showToast({
						title:'暂无视频',
						icon:'none'
					})
					return
				}
				uni.navigateTo({
					url:`/pages/activity/playVideo?url=` + JSON.stringify(this.info.draw_video)
				})
			},
			//设置二维码本地路径
			setQrcodeImg(v){
				this.localQrcodePath=v;
			},
			// 复制邀请码
			copyInviteUrl() {
				this.invitShow = false
				this.$tools.copyText(this.invitaion_code)
			},
			// 绘制
			draw_start(code){
				this.invitShow = false
				if(this.posterImg){
					this.drawAccomplish(this.posterImg)
					return
				}
				uni.showLoading({ title:'绘制中...' })
				this.isDraw = true;
				console.log(this.appConfig);
				let bgImg = this.$originOssUrl + this.appConfig.share_bac_iamge;
				let codeImg = this.invitaion_code;
				this.canvasData = [
					{ type: 'rect', attr: { color: '#fff', x: 0, y: 0, width: 343, height: 526 } },
					{ type: 'image', attr: { image: bgImg, x: 0, y: 0, width: 343, height: 526 } },
					{ type: 'image', attr: { image: this.localQrcodePath, x: 245, y: 400, width: 80, height: 80 } },
				]
			},
			
			//绘制完成
			drawAccomplish(url) {
				if(!this.posterImg) uni.hideLoading();
				this.posterImg = url;
				this.showPoster = true;
				
				//#ifdef H5
					let ua = navigator.userAgent.toLowerCase();
					if (ua.indexOf('micromessenger') != -1){
						uni.$u.toast('长按保存到系统相册')
						return
					}
					let a = document.createElement('a')
					a.setAttribute('download', "")
					a.setAttribute('href', url)
					document.body.appendChild(a);
					a.style.display = 'none'
					a.click()
					document.body.removeChild(a)
					uni.$u.toast('图片已保存到系统相册')
				//#endif
				//#ifndef H5
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success() {
							uni.$u.toast('图片已保存到系统相册')
						},
						fail(err){
							console.log(err)
						}
					})
				//#endif
			}
		}
	}
</script>
<style>
	page {
		background-color: #FFCD85;
	}
</style>
<style lang="scss" scoped>
	.draw {
		.nav-right {
			.record-btn {
				width: 60rpx;
				height: 60rpx;
				background: rgba(#020202,0.4);
				border-radius: 20rpx;
				font-weight: 500;
				font-size: 22rpx;
				color: #fff;
				text-align: center;
				line-height: 60rpx;
			}
		}
		.draw-down-box {
			background-color: #FFCD84;
			padding: 0 16rpx;
			border-radius: 48rpx;
			margin-top: -140rpx;
			position: relative;
			.status-text-bg {
				width: 100%;
				height: 126rpx;
				background-image: url($IMG_URL + '/static/draw/status-text-bg.png');
				background-size: 100% 100%;
				padding: 24rpx 22rpx;
				.status-text {
					width: 318rpx;
					height: 78rpx;
					background-image: url($IMG_URL + '/static/draw/status-text.png');
					background-size: 100% 100%;
					padding: 0 0 24rpx 82rpx;
					font-family: YouSheBiaoTiYuan, YouSheBiaoTiYuan;
					font-weight: 600;
					font-size: 32rpx;
					color: #FFFFFF;
					line-height: 78rpx;
				}
			}
			.time__item {
				background: #FBE7DC;
				border-radius: 18rpx;
				font-family: OPPO Sans 4.0, OPPO Sans 40;
				font-weight: 600;
				font-size: 36rpx;
				color: #F44A6C;
				padding: 24rpx 20rpx;
			}
			.status-btn-box {
				margin-top: 68rpx;
				.again_box {
					width: 100%;
					height: 80rpx;
					background: linear-gradient( 90deg, rgba(253,173,54,0) 0%, #FDAD36 49%, rgba(253,173,54,0) 100%);
					background-size: 100% 100%;
					background-repeat: no-repeat;
					text-align: center;
					line-height: 80rpx;
					font-size: 28rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					margin-top: 30rpx;
				}
			}
		}
		.invite-box {
			width: 100%;
			height: 148rpx;
			background-image: url($IMG_URL + '/static/draw/draw-invite-bg.png');
			background-size: 100% 100%;
			.invite-text {
				font-family: YouSheBiaoTiYuan, YouSheBiaoTiYuan;
				font-weight: 600;
				font-size: 40rpx;
				color: #4A1D2F;
			}
		}
		.status-text-bg {
			width: 100%;
			height: 126rpx;
			background-image: url($IMG_URL + '/static/draw/status-text-bg.png');
			background-size: 100% 100%;
			padding: 24rpx 22rpx;
		}
		.item-number {
			width: 62rpx;
			height: 82rpx;
			background: #F5F5F5;
			border-radius: 18rpx;
			text-align: center;
			line-height: 82rpx;
			font-size: 36rpx;
			font-family: OPPO Sans 4.0, OPPO Sans 40;
			font-weight: 600;
			color: #000;
		}
		.xuxian {
			flex: 1;
			border: 2rpx dotted #ADADAD;
			margin: 0 30rpx;
		}
	}
</style>